package com.demo.easytranslate;

import java.net.*;
import java.io.*;
import java.util.regex.*;

public class Translate {
	
	private String translatement;
	
	public static final String AUTO = "AUTO";
	
	public static final String ZH_CN2EN = "ZH_CN2EN";
	public static final String ZH_CN2JA = "ZH_CN2JA";
	public static final String ZH_CN2KR = "ZH_CN2KR";
	public static final String ZH_CN2FR = "ZH_CN2FR";
	public static final String ZH_CN2RU = "ZH_CN2RU";
	public static final String ZH_CN2SP = "ZH_CN2SP";
	
	public static final String EN2ZH_CN = "EN2ZH_CN";
	public static final String JA2ZH_CN = "JA2ZH_CN";
	public static final String KR2ZH_CN = "KR2ZH_CN";
	public static final String FR2ZH_CN = "FR2ZH_CN";
	public static final String RU2ZH_CN = "RU2ZH_CN";
	public static final String SP2ZH_CN = "SP2ZH_CN";
	
	private final String user_agent = "Mozilla/5.0 (Linux; U; Android 8.1.0; zh-cn; vivo X20Plus A Build/OPM1.171019.011) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/66.0.3359.126 MQQBrowser/10.1 Mobile Safari/537.36";
	
	private final String YOUDAO = "http://m.youdao.com/translate";
	
	private String host = YOUDAO;
	
	public Translate(String translatement) {
		this.translatement = translatement;
	}
	
	public String translate(String type) {
		try {
			URL url = new URL(host);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			conn.setRequestProperty("User-Agent",user_agent);
			conn.connect();
			
			String body = "inputtext=" + translatement + "&type=" + type;
			
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));
			
			bw.write(body);
			bw.close();
			
			if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
				
				String content = "";
				String source = "";
				
				while((content = br.readLine()) != null) {
					source += content;
					//System.out.println(content);
				}
				
				Pattern pattern = Pattern.compile("<ul id=\"translateResult\">.*</li>");
				Matcher matcher = pattern.matcher(source);
				
				if(matcher.find()) {
					Matcher match = Pattern.compile("<li>(.*?)</li>").matcher(matcher.group());
					
					if(match.find()) {
						return match.group().replace("<li>","").replace("</li>","");
					}
				}
				
				br.close();
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return "出现异常";
	}
}
//进行了修改
